/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

<template>
  <div class='player'>
    <div class='time_schedule'>
      <div class='progress-container' v-interaction='{
        handlers: {
          onDragStart: handleDragStart,
          onDragMove: handleDragMove,
          onClick: handleClick,
          onScroll: handleScrollStart
        },
        configs: {
          enableDrag: true,
          enableClick: true,
          enableScroll: true
        },
      }' ref='scheduleRef'>
        <div class='progress-track'>
          <div class='progress-buffered' :style="{ width: getWidth + '%' }"></div>
          <div class='progress-fill' :style="{ width: getOffLeft + '%' }"></div>
        </div>
        <div class='time'>
          <span class='current-time'>{{ musicPlayTime }}</span>
          <span class='duration'>{{ musicTime }}</span>
        </div>
      </div>
    </div>
    <div class='play_icon'>
      <img src='../../assets/images/repeat.svg' alt='' />
      <img @click='previousTrack' src='../../assets/images/left.svg' alt='' />
      <img v-if='isPlayLocal === 1' @click='playMusic(0)' src='../../assets/images/pause.svg' alt='' />
      <img v-if='isPlayLocal === 0' @click='playMusic(1)' src='../../assets/images/play.svg' alt='' />
      <img @click='theNextSong' src='../../assets/images/forward_end_fill.svg' alt='' />
      <img src='../../assets/images/music_note_list.svg' alt='' />
    </div>
    <div class='play_nav_icon'>
      <img src='../../assets/images/share_play.svg' alt='' />
      <img src='../../assets/images/bell.svg' alt='' />
      <img src='../../assets/images/arrow_down_circle.svg' alt='' />
      <img src='../../assets/images/dot.svg' alt='' />
    </div>
  </div>
</template>

<script lang='ts'>
import Vue from 'vue';
import { formatTime } from '../../utils/common';

export default Vue.extend({
  props: {
    deviceType: {
      type: String,
      default: 'mobile',
    },
    isPlay: {
      type: Number,
      default: 0,
    },
    musicId: {
      type: Number,
      default: 1,
    },
    musicListNum: {
      type: Number,
      default: 50,
    },
  },
  data() {
    return {
      musicTime: '',
      musicPlayTime: '0:00',
      musicList: [],
      oneMusic: {},
      getWidth: 0,
      getOffLeft: '0',
      scheduleWidth: 0,
      startX: 0,
      isPlayLocal: this.isPlay,
      musicIdLocal: this.musicId,
      musicListNumLocal: this.musicListNum,
      player: null
    };
  },
  methods: {
    playMusic(value) {
      this.isPlayLocal = value;
      if (value === 0) {
        this.player.pause();
      } else {
        this.player.play();
        this.player.onTimeUpdate(this.handleTimeUpdate);
      }
      this.$emit('updateIsPlay', this.isPlayLocal);
    },
    handleDragStart(e) {
      this.player.pause();
      this.emit('updateIsPlay', this.isPlayLocal);
      e.dataTransfer.setData('text/plain', '');
      const img = new Image();
      img.src =
        '';
      e.dataTransfer?.setDragImage(img, 0, 0);
      e.dataTransfer.effectAllowed = 'move';
    },
    handleDragEnter(e) {
      // console.debug(e, 'enter');
    },
    handleDragMove(e) {
      const currentProgress = ((e.clientX - this.startX) / this.scheduleWidth) * 100;
      this.culProgress(currentProgress);
    },
    handleScrollStart(e) {
      const currentProgress = ((e.windowX - this.startX) / this.scheduleWidth) * 100;
      this.culProgress(currentProgress);
    },
    previousTrack() {
      this.player.pause();
      if (this.musicIdLocal !== 1) {
        this.musicIdLocal--;
        this.updateMusic();
      }
    },
    theNextSong() {
      this.player.pause();
      if (this.musicIdLocal !== this.musicList.length) {
        this.musicIdLocal++;
        this.updateMusic();
      }
    },
    updateMusic() {
      this.oneMusic = this.musicList[this.musicIdLocal - 1];
      this.player.setCurrentMusicId(this.musicIdLocal);
      this.player.seekTo(0);
      this.player.play();
      this.player.onTimeUpdate(this.handleTimeUpdate);
      this.isPlayLocal = 1;
      this.$emit('updateIsPlay', this.isPlayLocal);
      this.$emit('updateMusic', this.musicIdLocal);
    },
    seek(num) {
      const newTime = this.player.getCurrentTime() + num;
      this.player.seekTo(newTime);
      this.musicPlayTime = formatTime(newTime);
    },
    keyIncident(ev) {
      ev.preventDefault();
      switch (ev.key) {
        case 'ArrowUp':
          this.previousTrack();
          break;
        case 'ArrowDown':
          this.theNextSong();
          break;
        case 'ArrowLeft':
          if (this.player.getCurrentTime() - 5 < 0) {
            this.player.seekTo(0);
            this.musicPlayTime = formatTime(0);
          } else {
            this.seek(-5);
          }
          break;
        case 'ArrowRight':
          if (this.player.getCurrentTime() + 5 > this.player.getDuration()) {
            this.player.seekTo(this.player.getDuration());
            this.musicPlayTime = formatTime(this.player.getDuration());
          } else {
            this.seek(5);
          }
          break;
        case 'Enter':
          this.playMusic(1);
          break;
        case 'Escape':
          this.$router.push({
            path: '/musicList',
            query: {
              isPlay: this.isPlayLocal,
              musicId: this.musicIdLocal,
            },
          });
          break;
        case ' ':
          this.isPlayLocal = 0;
          this.player.pause();
          this.$emit('updateIsPlay', this.isPlayLocal);
          break;
      }
    },
    handleTimeUpdate(time, dur) {
      const progress = (time / dur) * 100;
      this.getWidth = progress;
      this.musicPlayTime = formatTime(time);
    },
    handleClick(e) {
      const currentProgress = ((e.windowX - this.startX) / this.scheduleWidth) * 100;
      this.culProgress(currentProgress);
    },
    culProgress(currentProgress) {
      if (currentProgress > 0 && currentProgress <= 100) {
        const newTime = (currentProgress * this.player.getDuration()) / 100;
        this.getWidth = currentProgress;
        this.player.seekTo(newTime);
        this.musicPlayTime = formatTime(newTime);
      }
    }
  },
  mounted() {
    const MusicList = sessionStorage.getItem('musicList');
    if (MusicList) {
      this.musicList = JSON.parse(MusicList);
      this.$store.commit('addMusiclist', this.musicList);
    }
    this.oneMusic = this.musicList[this.musicIdLocal - 1];
    this.musicTime = formatTime(this.player.getDuration());

    this.player.seekTo(0);
    this.player.pause();
    if (this.isPlay) {
      this.player.play();
      this.player.onTimeUpdate(this.handleTimeUpdate);
    }

    if (this.player.getCurrentTime() > 0 && this.isPlayLocal === 0) {
      const progressPercentage =
        (this.player.getCurrentTime() / this.player.getDuration()) * 100;
      this.getWidth = progressPercentage;
      this.musicPlayTime = formatTime(this.player.getCurrentTime());
    }
    this.$nextTick(() => {
      this.startX = this.$refs.scheduleRef.getBoundingClientRect().left;
      this.scheduleWidth = this.$refs.scheduleRef.offsetWidth;
    });
    if (this.isPlayLocal) {
      this.player.play();
      this.player.onTimeUpdate(this.handleTimeUpdate);
    }
    document.addEventListener('keydown', this.keyIncident);
    this.$once('hook:beforeDestroy', () => {
      document.removeEventListener('keydown', this.keyIncident);
    });
    document.oncontextmenu = function (e): boolean {
      e.preventDefault();
      return false;
    };
  },
  created() {
    this.player = this.$musicPlayer;
  },
});
</script>

<style lang='less' scoped>
@import './index.less';
</style>